<template>
  <div style="display:inline-block;" @click="onExport">
    <el-button type="warning" v-if="type=='button'" size="small">导出</el-button>
    <i class="el-icon-download pointer" v-if="type=='icon'"></i>
    <a href="javascript:;" class="text-primary" v-if="type=='text'">导出</a>
  </div>
</template>

<script>
import {
  postExport,
  getExport
} from './exportMethods'
import { exportUrl } from '@/api'
export default {
  props: {
    exportQuery: {
      type: Object,
      default () {
        return {
          query: {},
          url: '',
          fileName: '',
          total: null
        }
      }
    },
    type: {
      type: String,
      default: 'button'
    },
    method: {
      type: String,
      default: 'post'
    }
  },
  data () {
    return {
      notification: null,
      timer: null,
      queryResult: {
        fileKey: null
      },
      dealIdx: 0,
      fileKey: null
    }
  },
  watch: {
    exportQuery () {
      if (this.type === 'text') return
      this.exportOrder()
    }
  },
  methods: {
    onExport () {
      if (this.type !== 'text') return
      this.exportOrder()
    },
    async exportOrder () {
      let _vm = this
      let params = Object.assign({}, _vm.exportQuery.query)
      let res = await postExport(params, _vm.exportQuery.url)
      this.fileKey = res.fileKey
      this.queryExport(this.fileKey)
    },
    apiDownload (fileKey, fileUrl) {
      window.location.href = `${fileUrl}`
      this.clearQuery()
    },
    async queryExport (fileKey) {
      let _vm = this
      getExport({ fileKey }, exportUrl.queryExport)
        .then(res => {
          this.queryResult = res
          if (this.queryResult.fileState === 3) {
            _vm.apiDownload(this.fileKey, res.fileUrl)
          } else {
            this.dealIdx = this.queryResult.dealIdx
            if (!this.notification) {
              this.notification = this.$notify({
                title: '数据导出中...',
                message: `已导出数据${this.dealIdx}条!`,
                duration: 0,
                showClose: false
              })
            } else {
              this.notification.message = `已导出数据${this.dealIdx}条!`
            }
            this.timer && clearInterval(this.timer)
            this.timer = setInterval(function () {
              _vm.queryExport(_vm.fileKey)
            }, 1000)
          }
        })
        .catch(e => {
          this.clearQuery()
        })
    },
    clearQuery () {
      this.timer && clearInterval(this.timer)
      this.timer = null
      this.fileKey = null
      this.notification && this.notification.close()
    }
  }
}
</script>
